import cv2 as cv
import numpy as np


def hat_gray_demo(image):
    gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY)
    kernel = cv.getStructuringElement(cv.MORPH_RECT,(15,15))
    # dst = cv.morphologyEx(gray,cv.MORPH_TOPHAT,kernel)
    dst = cv.morphologyEx(gray, cv.MORPH_BLACKHAT, kernel)
    limg = np.array(gray.shape,np.uint8)
    limg = 20
    dst = cv.add(dst,limg)
    cv.imshow('open_demo',dst)


def hat_binary_demo(image):
    gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY)
    ret,binary = cv.threshold(gray,0,255,cv.THRESH_BINARY|cv.THRESH_OTSU)
    kernel = cv.getStructuringElement(cv.MORPH_RECT,(3,3))
    # dst = cv.morphologyEx(binary,cv.MORPH_TOPHAT,kernel)
    # dst = cv.morphologyEx(binary, cv.MORPH_BLACKHAT, kernel)
    dst = cv.morphologyEx(binary, cv.MORPH_GRADIENT, kernel) #gradient
    cv.imshow('open_demo',dst)


def gradient_demo(image):
    kernel = cv.getStructuringElement(cv.MORPH_RECT,(3,3))
    dm = cv.dilate(image,kernel)
    em = cv.erode(image,kernel)
    internal_gradient = cv.subtract(image,em)
    external_gradient = cv.subtract(dm,image)
    cv.imshow('internal_gradient',internal_gradient)
    cv.imshow('external_gradient',external_gradient)


src = cv.imread('pic1.png',1)
cv.namedWindow('demo',cv.WINDOW_AUTOSIZE)
cv.imshow('demo',src)
gradient_demo(src)
cv.waitKey(0)
cv.destroyAllWindows()